package com.lalameow.loreattr.attribute.attribute.valueattribute;

import com.lalameow.common.util.LaLaMeowUtil;
import com.lalameow.loreattr.attribute.attribute.AbstractValueAttribute;
import com.lalameow.loreattr.attribute.entity.EntityAttribute;
import com.lalameow.loreattr.attribute.util.LoreUtils;
import org.bukkit.entity.LivingEntity;
import org.bukkit.inventory.ItemStack;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Author: SettingDust
 * Date: 2017/6/30.
 */
public class AttributeDodge extends AbstractValueAttribute {
    private final Pattern dodgeRegex = Pattern.compile("[+](\\d+)[%][ ](" + entityAttribute.getKeyword() + ")");

    public AttributeDodge() {
        super(EntityAttribute.getAttribute("dodge"));
    }

    @Override
    public double getAttribute(LivingEntity entity) {
        if (!entity.isValid()) {
            return 0;
        }
        return getValue(LoreUtils.getLore(entity, false, true));
    }

    @Override
    public double getAttribute(ItemStack itemStack) {
        return getValue(LoreUtils.getLore(itemStack));
    }

    @Override
    public double getValue(List<String> lore) {
        Integer dodgeBonus = 0;
        for (String s : lore) {
            Matcher matcher = dodgeRegex.matcher(s.toLowerCase());
            if (matcher.find()) {
                dodgeBonus += Integer.valueOf(matcher.group(1));
            }
        }
        return dodgeBonus;
    }

    public boolean isDodge(LivingEntity entity) {
        return LaLaMeowUtil.random(getAttribute(entity));
    }
}
